import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    cart: [
      { id: 1, name: '手机', price: 1000, quantity: 1 },
      { id: 2, name: '电脑', price: 2000, quantity: 1 },
      { id: 3, name: '键盘', price: 200, quantity: 2 }
    ]
  },
  mutations: {
    add_item(state, item) {
      let index = state.cart.findIndex(i => i.id === item.id);
      if (index > -1) {
        state.cart[index].quantity += item.quantity;
      } else {
        state.cart.push({ ...item, quantity: item.quantity });
      }
    },
    remove_item(state, id) {
      let index = state.cart.findIndex(i => i.id === id);
      if (index > -1) {
        state.cart.splice(index, 1);
      }
    },
    update_item(state, { id, quantity }) {
      let item = state.cart.find(i => i.id === id);
      if (item) {
        item.quantity = quantity;
      }
    }
  },
  getters: {
    cartItems: state => state.cart,
    totalPrice: state => state.cart.reduce((total, item) => total + item.price * item.quantity, 0)
  }
});